package com.atguigui.leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 658.找到 K 个最接近的元素
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/8/25 8:33
 */
public class P658FindKClosestElements {

    public static void main(String[] args) {
        Solution solution = new P658FindKClosestElements().new Solution();
        // TO TEST
    }

    class Solution {
        public List<Integer> findClosestElements(int[] arr, int k, int x) {
            List<Integer> list = new ArrayList<>();

            for (int i : arr) {
                list.add(i);
            }

            Collections.sort(list, new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    if (Math.abs(x - o1) != Math.abs(x - o2)) {
                        return Math.abs(x - o1) - Math.abs(x - o2);
                    } else {
                        return o1 - o2;
                    }
                }
            });

            List<Integer> ans = list.subList(0, k);
            Collections.sort(ans);

            return ans;
        }
    }
}
